#!/usr/bin/env python
# encoding: utf-8

from django.contrib.gis.geos import GEOSGeometry

def get_lookat(geometry, begin=False, end=False):
    return """<LookAt>
		<gx:TimeSpan>
			<begin>2010-04-22T10:00:00Z</begin>
			<end>2010-06-18T21:34:00Z</end>
		</gx:TimeSpan>
		<longitude>-87.6797361326919</longitude>
		<latitude>29.75339314157766</latitude>
		<altitude>0</altitude>
		<range>1418004.228883875</range>
		<tilt>0</tilt>
		<heading>1.146240875396169</heading>
		<altitudeMode>relativeToGround</altitudeMode>
		<gx:altitudeMode>relativeToSeaFloor</gx:altitudeMode>
	</LookAt>
	"""    
    
    

def create_kmz(kml, zippath='kml/doc.kml'):
    """
    Given a KML string and a "/" seperated path like "FOLDERNAME/doc.kml",
    creates a zipped KMZ archive buffer that can be written directly to a 
    django response object
    """
    import tempfile
    from cStringIO import StringIO
    import zipfile

    # write out the kml to tempfile
    #The Problem:  for Windows, we need to close the file before we can access it again below (via zipout.write)
    #   this caused a Permissions Error when running from the local dev server (on Windows)
    #   as Windows considered the unclosed file to already be in use (and therefore unaccessible) 
    #The Solution: adding 'delete=False' to tempfile.NamedTemporaryFiles for developing environments using Python 2.6(sf 2-16-10)
    #   this will only happen if the user is using Python 2.6, previous versions of Python will treat the code as it was
    #   (this delete parameter isn't available until python 2.6)
    #if the development environment is using 2.5 or earlier, then the temp file will still be closed via kmlfile.close()
    #if the development environment is using 2.6 then the temporary file is deleted manually via os.unlink(kmlfile.name) (see below)
    #This was reported (and perhaps more fully explained) in Issue 263
    python26 = True
    try:
        kmlfile = tempfile.NamedTemporaryFile(delete=False)
    except:
        kmlfile = tempfile.NamedTemporaryFile()
        python26 = False
    kmlfile.write(kml.encode('utf-8'))
    kmlfile.flush()
    if python26:
        kmlfile.close() 
    
    # zip it up into a kmz
    kmzbuffer = StringIO()
    zipout = zipfile.ZipFile(kmzbuffer,'w',zipfile.ZIP_DEFLATED)
    zipout.write(kmlfile.name, zippath.encode('ascii')) 
    zipout.close()

    # close out the tempfile
    if python26:
        import os 
        os.unlink(kmlfile.name) 
    else:
        kmlfile.close()
    # grab the content of the stringIO buffer
    kmz = kmzbuffer.getvalue()
    # close out the stringIO buffer
    kmzbuffer.close()

    return kmz